/* Includes ------------------------------------------------------------------*/
#include "SystemTick.h"
#include "Led.h"
#include "RF.h"
#include "Button.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define BUTTON_DEBOUNCE     100                             // 100ms
#define TIME_TO_LEARN       ( 2000 / BUTTON_DEBOUNCE )      // 2s

/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
U8 s_PrescaleCnt = 0;
U8 s_SwStatus;
U8 s_SwChange;

U8 s_LearnPrescaleCnt = 0;

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Public functions ----------------------------------------------------------*/

U8 Button_GetStatus(void)
{
    U8 status = 0;
    if( RESET == GPIO_ReadInputPin(BUTTON_PORT, BUTTON_PINS) ) status = BUTTON_ACTIVE;

    return( status );
}

void Button_TimerInterrupt(void)
{
    U8 newStatus;
    if (BUTTON_DEBOUNCE <= ++s_PrescaleCnt)
    {
        s_PrescaleCnt = 0;

        if ( s_LearnPrescaleCnt < 0xFF ) ++s_LearnPrescaleCnt;

        newStatus = Button_GetStatus();
        s_SwChange = newStatus ^ s_SwStatus;
        s_SwStatus = newStatus;
    }
}


void Button_Init(void)
{
    // Initialize I/Os in Output Mode
    GPIO_Init(BUTTON_PORT, BUTTON_PINS, GPIO_MODE_IN_PU_NO_IT);

    SysTick_Registration(&Button_TimerInterrupt);
    s_SwStatus = Button_GetStatus();
    s_SwChange = 0;
}


void Button_RunOne(void)
{
    if( NORMAL == Rf_GetMode() )
    {
        if (s_SwStatus & BUTTON_ACTIVE)
        {
            if ( TIME_TO_LEARN <= s_LearnPrescaleCnt )
            {
                Rf_SetMode( ENTER_LEARN );
            }
            Led_SetOutput( STATUS_LED, true );
        }
        else
        {
            s_LearnPrescaleCnt = 0;
        }
    }

    s_SwChange = 0;
}
